package logic

import (
	"context"
	"fmt"
	"github.com/2103A/message/user"
	"time"
	"wsyxapi/client"
	"wsyxapi/utils"

	"wsyxapi/internal/svc"
	"wsyxapi/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func check(req *types.UserRegisterRequest) error {
	if req.UserMobile == "" {
		return fmt.Errorf("手机号不能为空")
	}
	if req.UserName == "" {
		return fmt.Errorf("用户名不能为空")
	}
	if req.UserPassword == "" {
		return fmt.Errorf("密码不能为空")
	}
	return nil
}

func (l *RegisterLogic) Register(req *types.UserRegisterRequest) (resp *types.UserRegisterResponse, err error) {
	// todo: add your logic here and delete this line
	err = check(req)
	if err != nil {
		return nil, err
	}

	info, err := client.UserRegister(context.Background(), &user.UserRegisterRequest{
		UserName:     req.UserName,
		UserMobile:   req.UserMobile,
		UserPassword: req.UserPassword,
	})
	if err != nil {
		fmt.Println(err)
		return nil, err
	}

	fmt.Println("*******************info")
	fmt.Println(info)
	//info  转成字符串
	token, err := utils.GetJwtToken(time.Now().Unix(), int64(60*60*24*30), info.Data.UserId)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}

	return &types.UserRegisterResponse{
		ID:         int(info.Data.UserId),
		UserName:   info.Data.UserName,
		UserMobile: info.Data.UserMobile,
		Token:      token,
	}, nil
}
